package service

import (
	"errors"

	"gitee.com/sansaniot/ssiot-core/facade/env"
	"gorm.io/gorm"

	cDto "ssdevice/common/dto"
	"ssdevice/common/enums"
	"ssdevice/common/utils"
	"ssdevice/internal/device/models"
	"ssdevice/internal/device/models/query"
)

// 添加软网关 - 添加服务
func ctrlSoftGatewayServe(dev *models.SysDev, svcCtrl enums.SvcCtrlEnum) error {
	webUrl := env.ConfigOperator.GetString("settings.application.weburl")
	if len(webUrl) == 0 {
		return errors.New("微服务管理无法建立连接")
	}
	param := make(map[string]interface{})
	switch svcCtrl {
	case enums.Add:
		param["arg"] = "-sn " + dev.Sn
		param["svcType"] = "applet"
		fallthrough
	case enums.Modify:
		param["name"] = dev.Name
		param["instanceId"] = dev.Sn
	case enums.Remove:
		param["instanceId"] = dev.Sn
	default:
		return nil
	}
	header := make(map[string]string)
	header["Authentication"] = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjIwMzkwMTc1MjYsIm9yaWdfaWF0IjoxNjc5MDE3NTI2LCJ1c2VybmFtZSI6ImFkbWluIn0.-BGpKJPVLGS-iAMz6VCeKqYhtKaor_zaa-tbOgImTII"
	var resultJson interface{}
	err := utils.HttpPostJson(webUrl+"/api/service/"+svcCtrl.Get().Cmd, param, header, &resultJson)
	if err != nil {
		return errors.New("微服务管理接口请求失败," + err.Error())
	}
	if resultJson == nil {
		return errors.New("微服务管理接口请求未响应")
	}
	resp := resultJson.(map[string]interface{})
	if resp["code"] == nil || resp["code"].(float64) != 200 {
		tmpErr := errors.New("微服务管理接口请求异常:" + resp["message"].(string))
		return tmpErr
	}
	return nil
}

// 获取产品关联的设备SN
func getProductRelateSns(tx *gorm.DB, productIds, snList *[]string) error {
	dev := &models.SysDev{}
	devProduct := &models.SysDevProduct{}
	dev.Orm = tx
	devProduct.Orm = tx
	devList := make([]models.SysDev, 0)
	productList := make([]models.SysDevProduct, 0)
	if err := devProduct.FindList(&productList, cDto.MakeCondition(query.SysProductQuery{IdIn: *productIds})); err != nil {
		return err
	}
	productModels := make([]string, 0)
	for _, v := range productList {
		productModels = append(productModels, v.ProductModel)
	}
	if err := dev.FindList(&devList, cDto.MakeCondition(query.SysDevQuery{ProductModelIn: productModels})); err != nil {
		return err
	}
	for _, v := range devList {
		*snList = append(*snList, v.Sn)
	}
	return nil
}
